//
//  DYDownloadConfig.m
//  DYDownload
//
//  Created by 吴新庭 on 2019/5/9.
//  Copyright © 2019 iyinyue. All rights reserved.
//

#import "DYDownloadConfig.h"
#import "DYDownloadVersion.h"
#import "DYDownloadConfig+Schedule.h"

@interface DYDownloadConfig ()

@property (nonatomic, strong) DYDownloadVersionItem *localVersion;

@end

@implementation DYDownloadConfig

+ (DYDownloadConfig *)globalConfig {
    static dispatch_once_t onceToken;
    static DYDownloadConfig *global;
    dispatch_once(&onceToken, ^{
        global = [[DYDownloadConfig alloc] init];
    });
    return global;
}

+ (DYDownloadConfig *)defaultConfig {
    DYDownloadConfig *config = [[DYDownloadConfig alloc] init];
    return config;
}

- (DYDownloadConfig *)config:(void (NS_NOESCAPE ^)(DYDownloadConfig * _Nonnull))configBlock {
    configBlock(self);
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        _timeout = 60;
        _autoUnzip = YES;
    }
    return self;
}

- (NSString *)versionLocal {
    return self.localVersion.version;
}

#pragma mark - Private
- (DYDownloadVersionItem *)localVersion {
    if (!_localVersion) {
        if (self.versionKey.length > 0) {
            _localVersion = [DYDownloadVersion.version itemForKey:self.versionKey];
            
            // 如果路径为空，或者文件已被删除，重置版本号为最小
            NSString *targetFile = [self.target stringByAppendingPathComponent:self.path.lastPathComponent];
            if (![[NSFileManager defaultManager] fileExistsAtPath:targetFile]) {
                _localVersion.version = @"0";
                
                [DYDownloadVersion.version save];
            }
        }
    }
    return _localVersion;
}

@end
